//
//  FPCleanAccountController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/2/25.
//

#import "FPCleanAccountController.h"
#import <WebKit/WebKit.h>

@interface FPCleanAccountController () <WKNavigationDelegate , WKUIDelegate>

@property (nonatomic , strong) WKWebView *webView;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (nonatomic , strong) UIActivityIndicatorView *loadingView;

@end

@implementation FPCleanAccountController


- (UIActivityIndicatorView *)loadingView {
    
    if (!_loadingView) {
    
        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium];
        loadingView.hidesWhenStopped = YES;
        [self.view addSubview:_loadingView = loadingView];
//        loadingView.center = self.view.center;
        loadingView.frame = CGRectMake(SCREEN_WIDTH / 2.f - 37.f / 2.f, SCREEN_HEIGHT / 2.f - 37.f / 2.f, 37.f, 37.f);
    }
    return _loadingView;
}


- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
        
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr stopMonitoring];
    
    // 清缓存
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)initUI {
    
//    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    self.view.backgroundColor = UIColor.whiteColor;
    
    [self setTitle:@"注销" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    
    self.cancelBtn.clipsToBounds = YES;
    self.cancelBtn.layer.cornerRadius = 22.f;
    self.cancelBtn.backgroundColor = UIColor.whiteColor;
    self.cancelBtn.layer.borderWidth = 1.f;
    self.cancelBtn.layer.borderColor = [UIColor hexColor:@"#3A3A3A"].CGColor;
    [self.cancelBtn setTitleColor:[UIColor hexColor:@"#3A3A3A"] forState:(UIControlStateNormal)];
    
    self.confirmBtn.clipsToBounds = YES;
    self.confirmBtn.layer.cornerRadius = 22.f;
    self.confirmBtn.backgroundColor = MAIN_BLUE_COLOR;
    [self.confirmBtn setTitleColor:UIColor.whiteColor forState:(UIControlStateNormal)];
    
    self.webView = [[WKWebView alloc] init]; // 打开自适应 就要关掉这个alloc (重复了)
    
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    
    self.webView.frame = CGRectMake(0, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT-UIDevice.navigationFullHeight - UIDevice.safeDistanceBottom - 44.f - 12.f - 4.f);
    
    [self.view addSubview:self.webView];
    
    [self.cancelBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.confirmBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        [self cleanAccountAction];
    }];
    
    self.cancelBtn.hidden = YES;
    self.confirmBtn.hidden = YES;
    
    [MBManager showLoading];
    [FPProtocolModel getProtocolWithType:(FPProtocolTypeCleanAccount) success:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
        [MBManager hideLoading];
        
        if (code == 200) {

            FPProtocolModel *model = list.firstObject;
            
            // 注销无需 token
            NSURLRequest *request = [NSURLRequest requestWithURL:[self exchangePercentURLString:model.address]];
            [self.webView loadRequest:request];
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    [self.loadingView startAnimating];
    NSLog(@"开始加载页面");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    [self startCountDownTimer];
    
    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
    NSLog(@"页面加载完成");
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
    NSLog(@"页面加载失败：%@", error.localizedDescription);
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
    NSLog(@"导航失败：%@", error.localizedDescription);
}

- (NSURL *)exchangePercentURLString:(NSString *)urlStr {
    
    NSMutableCharacterSet *set  = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [set addCharactersInString:@"#"];
    NSURL *URL = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:set]];
    
    return URL;
}

- (void)cleanAccountAction {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"确认注销账户？" preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"注销" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        
        [MBManager showLoading];
        [FPUserModel clearAccountWithID:@"" success:^(NSString * _Nonnull message, NSInteger code) {
            [MBManager hideLoading];
            
            if (code == 200) {
                
                [self showText:@"注销成功"];
                [[FPUserModel sharedUser] loginInvalid];
                
                // 删除控制器
                NSMutableArray *marr = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
                
                for (UIViewController *vc in marr) {
                
                    if ([vc isKindOfClass:NSClassFromString(@"FPSettingController")]) {
                        
                        [marr removeObject:vc];
                        break;
                    }
                }
                
                self.navigationController.viewControllers = marr;
                
                [[NSNotificationCenter defaultCenter] postNotificationName:LogoutNotification object:nil];
                [self performSelector:@selector(backAction) withObject:nil afterDelay:1.5f];
            }
            else {
                
                [self showText:message];
            }
            
        } failure:^(NSError * _Nonnull error) {
            [self showError:error];
        }];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - 开始倒计时 验证码
- (void)startCountDownTimer {
    
    self.cancelBtn.hidden = NO;
    self.confirmBtn.hidden = NO;
    
    NSUInteger countdownTime = 31;
    
    NSDate *oldDate = [NSDate date];
    // 倒计时时间
    __block NSInteger timeOut = countdownTime;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
        // 倒计时结束
        if (timeOut <= 0) {
            
            // 再次获取
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.confirmBtn setTitle:@"确认注销" forState:(UIControlStateNormal)];
                self.confirmBtn.userInteractionEnabled = YES;
                self.confirmBtn.enabled = YES;
                self.confirmBtn.backgroundColor = MAIN_BLUE_COLOR;
            });
        }
        // 正在倒计时
        else {
            
            NSDate *newDate = [NSDate date];
            NSTimeInterval timeInterva = [newDate timeIntervalSinceDate:oldDate];
            int seconds2 = (countdownTime -timeInterva);
            NSString *timeStr = [NSString stringWithFormat:@"%d",seconds2];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.confirmBtn setTitle:[NSString stringWithFormat:@"确认注销(%@)", timeStr] forState:UIControlStateNormal];
                self.confirmBtn.userInteractionEnabled = NO;
                self.confirmBtn.enabled = NO;
                self.confirmBtn.backgroundColor = [[UIColor hexColor:@"#0D6FFF"] colorWithAlphaComponent:.5f];
            });
            //bug 解决
            if (seconds2 <= 1) {
                timeOut = 1;
            }
            timeOut--;
        }
    });
    dispatch_resume(_timer);
}



@end
